package com.zagj.videocomparess;

import android.annotation.TargetApi;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.zagj.videocomparess.encode.AudioEncoder;
import com.zagj.videocomparess.utils.MediaMuxer;
import com.zagj.videocomparess.widget.CircularProgressView;

import java.io.File;
import java.io.IOException;
import java.net.URI;

import javax.xml.datatype.Duration;

public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback,
        Camera.PreviewCallback, View.OnClickListener {

    private SurfaceView surfaceView;
    private Button button;
    private SurfaceHolder holder;
    private Camera camera;
    //private CameraEncode cameraEncode;
    private Camera.Parameters parameters;

    private CircularProgressView mCapture;
    private AudioEncoder audioEncoder;
    public String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator;
    private String mSavePath = path + "hello1.mp4";
    private String video_path;
    private EasyVideoPlay easyVideoPlay;
    private int surfaceWidth;
    private int surfaceHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        video_path = getIntent().getStringExtra("path");
        button = (Button) findViewById(R.id.button);
        mCapture = (CircularProgressView) findViewById(R.id.mCapture);
        surfaceView = (SurfaceView) findViewById(R.id.surface);
        holder = surfaceView.getHolder();
        holder.addCallback(this);
        mCapture.setTotal(40);
        mCapture.setOnClickListener(this);
        button.setOnClickListener(this);
        easyVideoPlay = new EasyVideoPlay();
        easyVideoPlay.init(this);
    }

    private void startcamera(Camera mCamera) {
        if (mCamera != null) {
            try {
                mCamera.setPreviewCallback(this);
                mCamera.setDisplayOrientation(90);
                if (parameters == null) {
                    parameters = mCamera.getParameters();
                }
                parameters = mCamera.getParameters();
                parameters.setPreviewFormat(ImageFormat.NV21);
                parameters.setPreviewSize(width, height);
                mCamera.setParameters(parameters);
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @TargetApi(9)
    private Camera getBackCamera() {
        Camera c = null;
        try {
            c = Camera.open(0); // attempt to get a Camera instance
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c; // returns null if camera is unavailable
    }

    int width = 1280;

    int height = 720;

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        camera = getBackCamera();
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            surfaceWidth = surfaceView.getWidth();
            surfaceHeight = surfaceView.getHeight();
        } else {
            surfaceWidth = surfaceView.getHeight();
            surfaceHeight = surfaceView.getWidth();
        }

        // final String s = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator+"test.flv";

        /*cameraEncode = new CameraEncode();
        cameraEncode.prepare(384, 640);

        cameraEncode.start();*/
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        //cameraEncode.feed(data, System.nanoTime());

    }

    private boolean recordFlag = false;//是否正在录制
    private boolean pausing = false;

    int play_flags = -1;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mCapture:
                if (!recordFlag) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            play_flags = easyVideoPlay.play(video_path, holder.getSurface());

                        }
                    }).start();

                    audioEncoder = new AudioEncoder();
                    try {
                        audioEncoder.prepare();
                        audioEncoder.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    recordFlag = true;
                } /* else if (!pausing) {
                    audioEncoder.pause();
                    pausing = true;
                } else {
                    audioEncoder.resume();
                    pausing = false;
                }*/
                break;
            case R.id.button:
                String cmdline = "-i /storage/emulated/0/DCIM/cut.mp4 -i /storage/emulated/0/DCIM/hello1.mp4 -r 30 -t 5 /storage/emulated/0/DCIM/1234.mp4";
                String[] argv = cmdline.split(" ");
                Integer argc = argv.length;
                MediaMuxer.muxer(video_path,audioEncoder.getPath(), path + "1234.mp4", argc, argv);
                break;
        }
    }

    int timeCount = 0;
    private long timeStep = 50;//进度条刷新的时间
    int maxTime;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    maxTime = msg.arg1 * 1000;
                    mCapture.setTotal(msg.arg1 * 1000);
                    Log.e("setProgressSize: ", 0000 + "");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("run: ", 0000 + "");
                            while (timeCount <= maxTime && recordFlag) {
                                if (pausing) {
                                    continue;
                                }
                                try {
                                    mCapture.setProcess((int) timeCount);
                                    Thread.sleep(timeStep);
                                    timeCount += timeStep;
                                    Log.e("run: ", timeCount + "");
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    }).start();
                    break;
                case 1:
                    changeVideoSize(msg.arg1, msg.arg2);
                    break;
            }
        }
    };

    public void changeVideoSize(int wdith, int height) {
       /*int videoWidth = mediaPlayer.getVideoWidth();
       int videoHeight = mediaPlayer.getVideoHeight();  */

        int videoWidth = wdith;
        int videoHeight = height;
        //根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
        float max;
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            //竖屏模式下按视频宽度计算放大倍数值
            max = Math.max((float) videoWidth / (float) surfaceWidth, (float) videoHeight / (float) surfaceHeight);
        } else {
            //横屏模式下按视频高度计算放大倍数值
            max = Math.max(((float) videoWidth / (float) surfaceHeight), (float) videoHeight / (float) surfaceWidth);
        }

        //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
        videoWidth = (int) Math.ceil((float) videoWidth / max);
        videoHeight = (int) Math.ceil((float) videoHeight / max);

        //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(videoWidth, videoHeight);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
        surfaceView.setLayoutParams(layoutParams);
    }

    public void realizeSize(int width, int height) {
        Message message = new Message();
        message.what = 1;
        message.arg1 = width;
        message.arg2 = height;

        handler.sendMessage(message);
    }

    public void setProgressSize(int duruation) {

        Log.e("setProgressSize: ", "mCapture");
        maxTime = duruation * 1000;
        Message message = new Message();
        message.what = 0;
        message.arg1 = duruation;
        handler.sendMessage(message);

    }
}